package com.mr.orderclient.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mr.orderclient.api.ProductForOrderApi;
import com.mr.orderclient.entity.OrderDetail;
import com.mr.orderclient.entity.OrderMaster;
import com.mr.orderclient.entity.ProductInfo;
import com.mr.orderclient.exception.CustomException;
import com.mr.orderclient.from.OrderForm;
import com.mr.orderclient.service.OrderService;
import com.mr.orderclient.utils.ConstantEnum;
import com.mr.orderclient.utils.ResultVOUtil;
import com.mr.orderclient.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.util.*;

/**
 * Class: BuyerOrderController
 * User (作者):MRui
 * TODO (描述)：
 * Date 2018.09.21 23:50
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductForOrderApi ProductForOrderApi;

    @Autowired
    private RestTemplate restTemplate;
    /**
    * User (作者): MRui
    * TODO (描述)：创建订单
    * Data：2018.09.22 21:56
    */
    @PostMapping("/create")
    public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm, BindingResult bindingResult){
        //判断表单校验后有无错误
        if(bindingResult.hasErrors()){
            throw new CustomException(ConstantEnum.EXCEPTION_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        //将orderForm属性添加到orderMaster(对象转换)
        Gson gson = new Gson();
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setBuyerOpenid(orderForm.getOpenid());
        orderMaster.setBuyerName(orderForm.getName());
        orderMaster.setBuyerPhone(orderForm.getPhone());
        orderMaster.setBuyerAddress(orderForm.getAddress());

        try{
            orderMaster.setOrderDetailList(gson.fromJson("["+orderForm.getItems()+"]",
                    new TypeToken<List<OrderDetail>>(){}.getType()));
        } catch (Exception e){
            log.error("对象转换错误，String={}",orderForm.getItems());
            throw new CustomException(ConstantEnum.EXCEPTION_PARAM_ERROR);
        }
        if (CollectionUtils.isEmpty(orderMaster.getOrderDetailList())){
            throw new CustomException(ConstantEnum.EXCEPTION_CART_EMPTY);
        }
        //创搭订单
        OrderMaster createResult = orderService.create(orderMaster);
        Map<String,String> map = new HashMap<>();
        map.put("orderId",createResult.getOrderId());
        return ResultVOUtil.success(map);
    }
    /**
    * User (作者): MRui
    * TODO (描述)：订单列表
    * Data：2018.09.22 21:59
    */
    @PostMapping("/list")
    public ResultVO<List<OrderMaster>> list(@RequestParam("openid") String openid,
                                            @RequestParam(value = "page",defaultValue = "0") int page,
                                            @RequestParam(value = "size",defaultValue = "10") int size){
        if (StringUtils.isEmpty(openid)){
            log.error("【查询订单列表】，openid为空");
            throw new CustomException(ConstantEnum.EXCEPTION_PARAM_ERROR);
        }
        PageRequest request = PageRequest.of(page, size);
        Page<OrderMaster> orderList = orderService.getOrderList(openid, request);
        return ResultVOUtil.success(orderList.getContent());
    }
    /**
    * User (作者): MRui
    * TODO (描述)：完结订单
    * Data：2018-11-17 16:12
    */
    @PostMapping("/finish")
    public ResultVO<OrderMaster> finish(@RequestParam("orderId") String orderId){
        OrderMaster orderMaster = orderService.finishOrder(orderId);
        return ResultVOUtil.success(orderMaster);
    }

    /**
    * User (作者): MRui
    * TODO (描述)：订单详情
    * Data：2018.09.22 23:09
    */
    @PostMapping("/detail")
    public ResultVO<OrderMaster> detail(@RequestParam("openid") String openid,
                                        @RequestParam("orderId") String orderId){
        OrderMaster orderMaster = orderService.getOrder(openid,orderId);
        return ResultVOUtil.success(orderMaster);
    }

    /**
    * User (作者): MRui
    * TODO (描述)：取消订单
    * Data：2018.09.22 23:14
    */
    /*@PostMapping("/cancel")
    public ResultVO cancel(@RequestParam("openid") String openid,
                           @RequestParam("orderId") String orderId){
        OrderMaster orderMaster = orderService.getOrder(openid,orderId);
        orderService.cancelOrder(orderMaster);
        return ResultVOUtil.success();
    }*/
    /**
    * User (作者): MRui
    * TODO (描述)：服务之间通信测试方法
    * Data：2018-11-17 16:01
    */
    @GetMapping("/test")
    public List<ProductInfo> cancel(){
        //RestTemplate restTemplate = new RestTemplate();
        //String object = restTemplate.getForObject("http://product/product/product/test", String.class);
        List<String> a = new ArrayList<>();
        a.add("3");
        List<ProductInfo> test = ProductForOrderApi.findList(a);
        return test;
    }
}

